package io.renren.modules.generator.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.vortex.tool.httpclient.HttpMethodName;
import com.vortex.tool.httpclient.Protocol;
import com.vortex.tool.httpclient.VtxHttpClient;
import com.vortex.tool.httpclient.request.VtxHttpRequest;
import com.vortex.tool.httpclient.sign.VtxV1Signer;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.IPUtils;
import io.renren.constant.DeviceFinal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.generator.dao.DeviceGasDao;
import io.renren.modules.generator.entity.DeviceGasEntity;
import io.renren.modules.generator.service.DeviceGasService;


@Service("deviceGasService")
public class DeviceGasServiceImpl extends ServiceImpl<DeviceGasDao, DeviceGasEntity> implements DeviceGasService {

    private static Logger logger = LoggerFactory.getLogger(DeviceGasServiceImpl.class);
    @Autowired
    private DeviceGasDao deviceGasDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DeviceGasEntity> page = this.page(
                new Query<DeviceGasEntity>().getPage(params),
                new QueryWrapper<DeviceGasEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void putData() {
//        VtxHttpRequest request = new VtxHttpRequest();
//        request.withHttpMethod(HttpMethodName.GET);
//        request.withParams("deviceIds",new String[]{DeviceFinal.device_gas_code});//天瑞气体
//        try {
//            request.withUri(new URI(DeviceFinal.device_url));
//            VtxHttpClient client = new VtxHttpClient(DeviceFinal.credential, new VtxV1Signer(), Protocol.HTTP);
//            String result = client.execute(request);
//            logger.info("------------result:"+result);
//            JSONObject jsonObject = JSONObject.parseObject(result);
//            JSONArray jsonArray = jsonObject.getJSONObject("ret").getJSONArray(DeviceFinal.device_gas_code);
//            DeviceGasEntity deviceGasEntity;
//            for (int i = 0; i < jsonArray.size(); i++) {
//                QueryWrapper<DeviceGasEntity> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("device_code",jsonArray.getJSONObject(i).getString("code"))
//                .eq(
//                        "create_time",
//                        DateUtils.longToDate(
//                                Long.parseLong(jsonArray.getJSONObject(i).getString("time")),"yyyy-MM-dd HH"
//                            )
//                    );
//                deviceGasDao.delete(queryWrapper);
//                deviceGasEntity = new DeviceGasEntity();
//                deviceGasEntity.setDeviceCode(jsonArray.getJSONObject(i).getString("code"));
//                deviceGasEntity.setDeviceIndexName(DeviceFinal.gasMap.get(jsonArray.getJSONObject(i).getString("code")));
//                deviceGasEntity.setCreateTime(
//                        DateUtils.longToDate(Long.parseLong(jsonArray.getJSONObject(i).getString("time")),"yyyy-MM-dd HH")
//                );
//                deviceGasEntity.setDeviceValue(jsonArray.getJSONObject(i).getString("value"));
//                deviceGasDao.insert(deviceGasEntity);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public Object chartlist(String dateStr) throws ParseException {
        JSONObject jsonObject = new JSONObject();
        try {
            DateFormat fmt =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = fmt.parse(dateStr);
            JSONArray jsonArray;
            DeviceGasEntity deviceGasEntity;
            for(Map.Entry<String, String> entry : DeviceFinal.gasQuotaMap.entrySet()){
                jsonArray = new JSONArray();
                String mapKey = entry.getKey();
                String mapValue = entry.getValue();
                Calendar calendarZero = Calendar.getInstance();
                calendarZero.setTime(now);
                calendarZero.set(Calendar.HOUR_OF_DAY, 0);
                calendarZero.set(Calendar.MINUTE, 0);
                calendarZero.set(Calendar.SECOND, 0);
                Date zero = calendarZero.getTime();
                QueryWrapper<DeviceGasEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("device_code",mapKey)
                        .eq("create_time",zero);
                deviceGasEntity = deviceGasDao.selectOne(queryWrapper);
                if(Objects.isNull(deviceGasEntity)){
                    jsonArray.add("0");
                }else{
                    jsonArray.add(deviceGasEntity.getDeviceValue());
                }
//                Date day=new Date();
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String s = df.format(now);
//                Date date = fmt.parse(dateStr);
                Date date = zero;
                GregorianCalendar calendar = new GregorianCalendar();
                int hour = calendar.get(Calendar.HOUR_OF_DAY);
                for (int i = 0; i < DateUtils.getHour(dateStr); i++) {//从1点开始到当前时间的小时
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    cal.add(Calendar.HOUR, 1);
                    date = cal.getTime();
                    String s1 = format.format(date);
                    logger.info("--------"+s1+"---------");
                    queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("device_code",mapKey)
                            .eq("create_time",date);
                    deviceGasEntity = deviceGasDao.selectOne(queryWrapper);
                    if(Objects.isNull(deviceGasEntity)){
                        jsonArray.add("0");
                    }else{
                        jsonArray.add(deviceGasEntity.getDeviceValue());
                    }
                }
                jsonObject.put(mapKey,jsonArray);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }


}